//
//  AppDelegate.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/8/30.
//

#import "AppDelegate.h"
#import "BRGuideVC.h"
#import "BROrderDetailViewController.h"
#import "BRSchemeManage.h"
#import "BRDevicePopupViewController.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate,FIRMessagingDelegate>
{
    BOOL _isFixingInterface; // 标志位：防止重复修复界面
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self br_config:application Options:launchOptions];
    
    [self didInitWindow];
    
    // TODO: 暂时屏蔽版本检查接口，避免404错误
    // [self checkVersion];
    
    // 添加延迟检查，确保界面正确显示
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checkAndFixMainInterface];
    });
    
    // 添加更频繁的检查
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checkAndFixMainInterface];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checkAndFixMainInterface];
    });
    
    return YES;
}

// 强制显示登录界面（容错方法）
- (void)forceShowLoginInterface {
    // 防止重复调用
    if (_isFixingInterface) {
        NSLog(@"⚠️ 正在修复界面中，跳过重复调用");
        return;
    }
    
    NSLog(@"强制显示登录界面...");
    
    // 确保在主线程执行
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self forceShowLoginInterface];
        });
        return;
    }
    
    // 检查当前是否已经是登录界面，避免重复创建
    UIViewController *currentRoot = self.window.rootViewController;
    if (currentRoot && [currentRoot isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)currentRoot;
        UIViewController *topVC = nav.topViewController;
        if ([topVC isKindOfClass:NSClassFromString(@"BRLoginViewController")]) {
            NSLog(@"当前已经是登录界面，无需重复创建");
            return;
        }
    }
    
    _isFixingInterface = YES;
    
    // 创建登录界面
    BRLoginViewController *loginVC = [[BRLoginViewController alloc] init];
    BRBaseNavController *nav = [[BRBaseNavController alloc] initWithRootViewController:loginVC];
    
    // 设置根视图控制器
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    // 强制刷新界面
    [self.window layoutIfNeeded];
    [nav.view setNeedsLayout];
    [nav.view layoutIfNeeded];
    
    // 延迟重置标志位
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self->_isFixingInterface = NO;
    });
    
    NSLog(@"强制显示登录界面完成");
}

// 检查并修复主界面显示问题
- (void)checkAndFixMainInterface {
    NSLog(@"检查主界面显示状态...");
    
    // 如果正在修复界面，跳过检查
    if (_isFixingInterface) {
        NSLog(@"正在修复界面中，跳过检查");
        return;
    }
    
    // 如果用户已登录，不要进行强制修复
    if (USERManager.isLogin) {
        NSLog(@"用户已登录，跳过界面修复检查");
        return;
    }
    
    if (!self.window.rootViewController) {
        NSLog(@"警告：根视图控制器为空，强制显示登录界面");
        [self forceShowLoginInterface];
        return;
    }
    
    if (!self.window.isKeyWindow) {
        NSLog(@"警告：窗口不是主窗口，尝试修复...");
        [self.window makeKeyAndVisible];
        return;
    }
    
    // 检查当前显示的控制器
    UIViewController *currentVC = self.window.rootViewController;
    if ([currentVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)currentVC;
        if (nav.viewControllers.count == 0) {
            NSLog(@"警告：导航控制器没有子控制器，强制显示登录界面");
            [self forceShowLoginInterface];
            return;
        }
        
        // 检查子控制器的视图是否正确加载
        UIViewController *topVC = nav.topViewController;
        if (!topVC.view || topVC.view.frame.size.width == 0 || topVC.view.frame.size.height == 0) {
            NSLog(@"警告：子控制器视图异常，强制显示登录界面");
            [self forceShowLoginInterface];
            return;
        }
        
        // 检查是否是登录界面，如果是登录界面且视图已加载，就不需要修复
        if ([topVC isKindOfClass:NSClassFromString(@"BRLoginViewController")]) {
            if (topVC.view && topVC.view.frame.size.width > 0 && topVC.view.frame.size.height > 0) {
                NSLog(@"当前是登录界面且视图正常，无需修复");
                return;
            }
        }
    }
    
    // 移除单纯依赖背景色的白屏检测，因为登录界面可能就是白色背景
    // 只检查视图是否真的异常（size为0）
    if (currentVC.view && 
        currentVC.view.frame.size.width > 0 && 
        currentVC.view.frame.size.height > 0) {
        NSLog(@"主界面显示状态正常");
        return;
    }
    
    // 只有真正异常时才修复
    NSLog(@"警告：界面视图异常，尝试修复");
    [self forceShowLoginInterface];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    NSLog(@"---applicationDidEnterBackground----");
    // 进入后台
    [BrezzeTimeManage stopappTimeInformation];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    NSLog(@"---applicationDidBecomeActive----");
    // 进入前台
    [BrezzeTimeManage starappTimeInformation];
    
    
//    [BROpenURL br_pasteInviteCode];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    
    NSString *urlStr = userActivity.webpageURL.absoluteString;
    NSLog(@"%@",urlStr);

    // 店主邀请
    [self appOpen:urlStr];
    

    
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    NSString *urlStr = url.absoluteString;
    NSLog(@"openURL= [%@]",urlStr);
    
    [self appOpen:urlStr];
    
    return YES;
}

- (BOOL)appOpen:(NSString *)urlStr {
    NSLog(@"📍 [URL Scheme] 处理URL: %@", urlStr);
    
    // 处理弹充电宝页面：youdianstar://devicePopup?orderUuid=xxx&deviceId=xxx
    if ([urlStr hasPrefix:@"youdianstar://devicePopup"]) {
        NSLog(@"📍 [弹充电宝] 检测到弹充电宝URL: %@", urlStr);
        
        // 提取参数
        NSString *orderUuid = [BRSchemeManage br_getParamByName:@"orderUuid" URLString:urlStr];
        NSString *deviceId = [BRSchemeManage br_getParamByName:@"deviceId" URLString:urlStr];
        
        NSLog(@"📍 [弹充电宝] 提取到参数 - orderUuid: %@, deviceId: %@", orderUuid ?: @"无", deviceId ?: @"无");
        
        // 延迟一点时间，确保界面已准备好
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前的导航控制器并跳转到弹充电宝页面
            UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            UINavigationController *navController = nil;
            
            // 查找导航控制器
            if ([rootVC isKindOfClass:[UINavigationController class]]) {
                navController = (UINavigationController *)rootVC;
            } else if ([rootVC isKindOfClass:[UITabBarController class]]) {
                UITabBarController *tabBarController = (UITabBarController *)rootVC;
                UIViewController *selectedVC = tabBarController.selectedViewController;
                if ([selectedVC isKindOfClass:[UINavigationController class]]) {
                    navController = (UINavigationController *)selectedVC;
                }
            } else if (rootVC.navigationController) {
                navController = rootVC.navigationController;
            }
            
            if (navController) {
                // 清除页面栈，只保留弹充电宝页面（从H5进入时）
                // 先pop到根视图，然后push弹充电宝页面
                [navController popToRootViewControllerAnimated:NO];
                
                // 创建弹充电宝页面并跳转
                BRDevicePopupViewController *popupVC = [[BRDevicePopupViewController alloc] init];
                popupVC.deviceId = deviceId;
                popupVC.orderUuid = orderUuid;
                [navController pushViewController:popupVC animated:YES];
                NSLog(@"📍 [弹充电宝] 已清除页面栈并跳转到弹充电宝页面，deviceId: %@, orderUuid: %@", deviceId ?: @"无", orderUuid ?: @"无");
            } else {
                NSLog(@"⚠️ [弹充电宝] 无法找到导航控制器，无法跳转");
            }
        });
        
        return YES;
    }
    
    // 处理订单详情跳转：youdianstar://order/detail?orderNo=xxx
    if ([urlStr hasPrefix:@"youdianstar://order/detail"]) {
        NSLog(@"📍 [订单详情] 检测到订单详情URL: %@", urlStr);
        
        // 提取订单号
        NSString *orderNo = [BRSchemeManage br_getParamByName:@"orderNo" URLString:urlStr];
        if (!orderNo || orderNo.length == 0) {
            NSLog(@"⚠️ [订单详情] 未能从URL中提取订单号: %@", urlStr);
            return YES;
        }
        
        NSLog(@"📍 [订单详情] 提取到订单号: %@", orderNo);
        
        // 发送通知，通知支付页面隐藏loading和恢复按钮状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BRPaymentCompleted" object:nil userInfo:@{@"orderNo": orderNo}];
        
        // 延迟一点时间，确保支付页面先处理完通知
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前的导航控制器并跳转到订单详情页
            UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            UINavigationController *navController = nil;
            
            // 查找导航控制器
            if ([rootVC isKindOfClass:[UINavigationController class]]) {
                navController = (UINavigationController *)rootVC;
            } else if ([rootVC isKindOfClass:[UITabBarController class]]) {
                UITabBarController *tabBarController = (UITabBarController *)rootVC;
                UIViewController *selectedVC = tabBarController.selectedViewController;
                if ([selectedVC isKindOfClass:[UINavigationController class]]) {
                    navController = (UINavigationController *)selectedVC;
                }
            } else if (rootVC.navigationController) {
                navController = rootVC.navigationController;
            }
            
            if (navController) {
                // 如果当前页面是支付页面（BRRentOrderViewController），先关闭它
                UIViewController *topVC = navController.topViewController;
                if (topVC && [topVC isKindOfClass:NSClassFromString(@"BRRentOrderViewController")]) {
                    NSLog(@"📍 [订单详情] 检测到当前在支付页面，先关闭支付页面");
                    [navController popViewControllerAnimated:NO];
                }
                
                // 创建订单详情页并跳转
                BROrderDetailViewController *orderDetailVC = [[BROrderDetailViewController alloc] init];
                orderDetailVC.orderNo = orderNo;
                [navController pushViewController:orderDetailVC animated:YES];
                NSLog(@"📍 [订单详情] 已跳转到订单详情页，订单号: %@", orderNo);
            } else {
                NSLog(@"⚠️ [订单详情] 无法找到导航控制器，无法跳转");
            }
        });
        
        return YES;
    }
    
    // 处理其他URL Scheme（原有的逻辑）
    if ([urlStr containsString:kOpenScheme] ||
        [urlStr containsString:BASE_URL]) {
        
        NSDictionary *dic = [BRSchemeManage br_urlDic:urlStr];
        if (dic != 0) {
            BRSchemeModel *dto = [BRSchemeModel mj_objectWithKeyValues:dic];
            
            USERManager.schemeModel = dto;
            
            kNotiPost(kPostSchemeOpenKey, nil);
        }
    }
    
    return YES;
    
}

#pragma mark - UNUserNotificationCenterDelegate --
// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
    
    // ...
    
    // Print full message.
    NSLog(@"userInfo = %@", userInfo);
    
    // Change this to your preferred presentation option
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    //  if (userInfo[kGCMMessageIDKey]) {
    //    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    //  }
    
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
    
    // Print full message.  ios 10 之后点击通知
    NSLog(@"userInfo = %@", userInfo);
    
    completionHandler();
}

// 静默通知处理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"userInfo = %@", userInfo);
    
    [self br_pushNoti:userInfo];
    
  completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - FireMessage Delegate --
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    // Notify about received token.
    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
    [[NSNotificationCenter defaultCenter] postNotificationName:
     @"FCMToken" object:nil userInfo:dataDict];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [FIRMessaging messaging].APNSToken = deviceToken;
}

#pragma mark - set rootWindow --
- (void)didInitWindow {
    NSLog(@"开始初始化主界面...");
    
    // 添加容错处理
    @try {
        UIViewController *rootVC = [self generateWindowRootViewController];
        if (rootVC) {
            self.window.rootViewController = rootVC;
            [self.window makeKeyAndVisible];
            NSLog(@"主界面初始化成功: %@", NSStringFromClass([rootVC class]));
            
            // 强制刷新界面
            [self.window layoutIfNeeded];
            [rootVC.view setNeedsLayout];
            [rootVC.view layoutIfNeeded];
            
            // 延迟检查界面是否正确显示
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (!rootVC.view || rootVC.view.frame.size.width == 0 || rootVC.view.frame.size.height == 0) {
                    NSLog(@"警告：界面初始化后仍然异常，强制显示登录界面");
                    [self forceShowLoginInterface];
                }
            });
            
        } else {
            NSLog(@"错误：无法生成根视图控制器，强制显示登录界面");
            [self forceShowLoginInterface];
        }
    } @catch (NSException *exception) {
        NSLog(@"主界面初始化异常: %@", exception);
        NSLog(@"⚠️ 异常情况下强制显示登录界面");
        [self forceShowLoginInterface];
    }
}

- (UIViewController *)generateWindowRootViewController {
    NSLog(@"开始生成根视图控制器...");
    
    // 添加容错处理
    @try {
        // 检查引导页
        if (![BRGuideVC isFirstInApp]) {
            NSLog(@"显示引导页");
            return [BRGuideVC new];
        }
        
        // 检查登录状态
        BOOL isLogin = USERManager.isLogin;
        NSLog(@"用户登录状态: %@", isLogin ? @"已登录" : @"未登录");
        
        // 打印详细的用户状态信息
        [USERManager br_logUserStatus];
        
        if (isLogin) {
            // 登录状态容错处理
            if (USERManager.loginTenantId.length == 0) {
                if (USERManager.tenantModel.platformId.length != 0) {
                    USERManager.loginTenantId = USERManager.tenantModel.platformId;
                    NSLog(@"容错：使用 platformId 作为 loginTenantId");
                }
            }
            
            // TODO: 暂时屏蔽系统配置接口，避免网络请求失败
            // [self br_reqSysConfigs];
            
            // 获取用户详细信息（新接口）
            [BRUserManager requestUserCenterInfo:^{
                NSLog(@"✅ 进入app时用户详细信息获取成功");
            } faile:^{
                NSLog(@"⚠️ 进入app时用户详细信息获取失败");
            }];
            
            // 账号通知订阅处理
            if ([BRNotificationManager isEnableNoti]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [BRNotificationManager subNoti:USERManager.userNotiKey status:^(BOOL isSucc) {
                        NSLog(@"通知订阅状态: %@", isSucc ? @"成功" : @"失败");
                    }];
                });
            }
            
            NSLog(@"显示主界面");
            BRHomeViewController *vc = [[BRHomeViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            BRBaseNavController *nav = [[BRBaseNavController alloc] initWithRootViewController:vc];
            return nav;
        }
        
        // 未登录状态
        NSLog(@"显示登录界面");
        // TODO: 暂时屏蔽系统配置接口，避免网络请求失败
        // [self br_reqSysConfigs];
        BRLoginViewController *vc = [[BRLoginViewController alloc] init];
        BRBaseNavController *nav = [[BRBaseNavController alloc] initWithRootViewController:vc];
        return nav;
        
    } @catch (NSException *exception) {
        NSLog(@"生成根视图控制器异常: %@", exception);
        NSLog(@"⚠️ 异常情况下强制显示登录界面");
        [self forceShowLoginInterface];
        return nil;
    }
}

#pragma mark - Other --
- (void)br_config:(UIApplication *)application Options:(NSDictionary *)launchOptions {
    
    // 添加异常捕获，防止应用崩溃
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    [self br_fireBaseConfig:application];
    
    [self br_setTheme];
    [self br_keybordSet];
    [self br_defaultConfig];
    [self br_googleMapsSet];
    [self br_stripeConfig];
    
    [BRRequestManager AFNReachability];
}

// 添加异常捕获处理
void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"应用异常: %@", exception);
    NSLog(@"异常堆栈: %@", [exception callStackSymbols]);
}

- (void)br_fireBaseConfig:(UIApplication *)application {
    //需要下载配置文件  GoogleService-Info.plist
    
    // 添加容错处理，即使 Firebase 配置失败也不影响应用启动
    
    // 添加容错处理，即使 Firebase 配置失败也不影响应用启动
    @try {
        [FIRApp configure];
        
        [FIRMessaging messaging].delegate = self;
            
        // TODO: 当前app暂时没有通知相关的功能，暂时注释掉通知权限请求
        /*
        if ([UNUserNotificationCenter class] != nil) {
          // iOS 10 or later
          // For iOS 10 display notification (sent via APNS)
          [UNUserNotificationCenter currentNotificationCenter].delegate = self;
          UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
              UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
          [[UNUserNotificationCenter currentNotificationCenter]
              requestAuthorizationWithOptions:authOptions
              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                // ...
              }];
        } else {
          // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
          UIUserNotificationType allNotificationTypes =
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
          UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
          [application registerUserNotificationSettings:settings];
        }

        [application registerForRemoteNotifications];
        */
        
        
        // TODO: 临时注释掉Firebase相关代码，专注于地图测试
        /*
        [[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
            if (error != nil) {
                NSLog(@"Error getting FCM registration token: %@", error);
            }else {
                NSLog(@"FCM registration token: %@", token);
            }
        }];
        [FIRMessaging messaging].autoInitEnabled = YES;
        */
        
        // TODO: 临时注释掉通知相关代码，专注于地图测试
        /*
        if (![BRNotificationManager isEnableNoti]) return;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [BRNotificationManager subDeviceNoti];
            

        });
        */
        
    } @catch (NSException *exception) {
        NSLog(@"Firebase 配置失败，但不影响应用启动: %@", exception);
    } @finally {
        // 即使 Firebase 配置失败，应用也能继续运行
    }
}

/// 配置支付key
- (void)br_stripeConfig {
    // Apple pay key - 修复：STPPaymentConfiguration 在新版本 Stripe 中已被移除
    // [[STPPaymentConfiguration sharedConfiguration] setAppleMerchantIdentifier:STPApplePayKey];
    
    // 支付key
    [STPAPIClient sharedClient].publishableKey = STPayKey;
}

- (void)br_setTheme {
    
    // 1. 先注册主题监听，在回调里将主题持久化存储，避免启动过程中主题发生变化时读取到错误的值
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleThemeDidChangeNotification:) name:QMUIThemeDidChangeNotification object:nil];
    
    // 2. 然后设置主题的生成器
    QMUIThemeManagerCenter.defaultThemeManager.themeGenerator = ^__kindof NSObject * _Nonnull(NSString * _Nonnull identifier) {
        if ([identifier isEqualToString:QDThemeIdentifierDefault]) return QMUIConfigurationTemplate.new;
        if ([identifier isEqualToString:QDThemeIdentifierDark]) return QMUIConfigurationTemplateDark.new;
        return nil;
    };
    QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierDefault;
    
}

- (void)br_defaultConfig {
    // 因为取消黑暗模式 默认状态栏为黑色
    [BRThemeManage br_isDarkStatusBar:YES];
    // 如果没缓存当前语言就默认配置
    [BRLanguageManager share];
}

- (void)br_keybordSet {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = NO;
    manager.enableAutoToolbar = YES;
}

- (void)br_googleMapsSet {
    // Google Maps API 必须在主线程调用
    if ([NSThread isMainThread]) {
        [GMSServices provideAPIKey:BRGMSMapKey];
        [GMSPlacesClient provideAPIKey:BRGMSMapKey];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [GMSServices provideAPIKey:BRGMSMapKey];
            [GMSPlacesClient provideAPIKey:BRGMSMapKey];
        });
    }
}

/// 获取系统相关配置
- (void)br_reqSysConfigs {
    // 获取系统相关配置
    [BRUserManager requestConfigs:^{

    } faile:^{

    }];
}

/// 收到推送后处理
- (void)br_pushNoti:(NSDictionary *)userInfo {
    if (USERManager.isLogin) {
        
        if([userInfo[@"msgType"] isEqualToString: @"1"]){ //租借
            
            
        }else if([userInfo[@"msgType"] isEqualToString: @"2"]){ //租借归还
            
        }else if([userInfo[@"msgType"] isEqualToString: @"9"]){ //自动扣支付
            
            kNotifyPost(kNotiRefeshHome);
        }
        
    }
}

- (void)br_platformAgreementShow {
    
  
    
    
}

#pragma mark - Notification --
- (void)handleThemeDidChangeNotification:(NSNotification *)notification {
    
    QMUIThemeManager *manager = notification.object;
    if (![manager.name isEqual:QMUIThemeManagerNameDefault]) return;
    
    [[NSUserDefaults standardUserDefaults] setObject:manager.currentThemeIdentifier forKey:QDSelectedThemeIdentifier];
    
    [QDThemeManager.currentTheme applyConfigurationTemplate];
    
//     主题发生变化，在这里更新全局 UI 控件的 appearance
    [QDCommonUI renderGlobalAppearances];
    
//     更新表情 icon 的颜色
    [QDUIHelper updateEmotionImages];
}

#pragma mark - 版本检测 --
// TODO: 暂时注释掉版本检测功能，直接从App Store更新
#if 0
- (void)checkVersion {
    //https://itunes.apple.com/lookup?id=1535224308   //youdianstar 20240211
    __weak __typeof__(self) weakSelf = self;
    // 原代码使用AFNetworking，已移除
    // 如需恢复此功能，请使用NSURLSession重写
    NSLog(@"版本检测功能已暂时禁用");
}
#endif

@end
